package io.xxx.xbutler.core.callback;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hy.corecode.idgen.WFGIdGenerator;
import io.xxx.xbutler.data.RobotRoomLogMapper;
import io.xxx.xbutler.data.RobotRoomMapper;
import io.xxx.xbutler.data.RoomMapper;
import io.xxx.xbutler.domain.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * <pre>
 * {
 *     "nType": 4505,
 *     "vcMerchantNo": "",
 *     "vcRobotWxId": "",
 *     "vcRobotSerialNo": "",
 *     "vcSerialNo": "",
 *     "nResult": 1,
 *     "vcResult": "SUCCESS",
 *     "Data": {
 *         "vcChatRoomSerialNo": "",
 *         "vcChatRoomId": "",
 *         "vcChatRoomName": "",
 *         "vcChatRoomBase64Name": "",
 *         "vcHeadImg": "",
 *         "vcFriendWxId": "",
 *         "vcFriendSerialNo": "",
 *         "vcNickName": {},
 *         "vcHeadImgUrl": "",
 *         "nUserCount": "",
 *         "vcAdminWxId": "",
 *         "vcAdminWxUserSerialNo": "",
 *         "ChatAdminType": "", // 群主微信类型（0 普通微信，1 企业微信）
 *         "IsEnterpriseChatroom": false
 * </pre>
 */
@Slf4j
@Component
public class _4505Handler implements CallbackHandler {

    @Resource
    private WFGIdGenerator idGenerator;

    @Resource
    private RoomMapper roomMapper;

    @Resource
    private RobotRoomMapper robotRoomMapper;

    @Resource
    private RobotRoomLogMapper robotRoomLogMapper;

    @Override
    public String name() {
        return "";
    }

    @Override
    public boolean supports(int type) {
        return type == 4505;
    }

    @Override
    public void handle(Callback callback) {
        String robotId = callback.getRobotId();
        String robotSerialNo = callback.getRobotSerialNo();
        JSONObject data = (JSONObject) callback.getData();
        String roomId = data.getString("vcChatRoomId");
        String roomSerialNo = data.getString("vcChatRoomSerialNo");
        String roomName = data.getString("vcChatRoomName");

        boolean roomExists = isExists(roomId);
        if (roomExists) {
            log.info("群信息已存在[contactId:{}]", roomId);
        } else {
            Room room = new Room()
                    .setId(roomId)
                    .setSerialNo(data.getString("vcChatRoomSerialNo"))
                    .setName(roomName)
                    .setAvatar(data.getString("vcHeadImg"))
                    .setOwnerId(data.getString("vcAdminWxId"))
                    .setOwnerSerialNo(data.getString("vcAdminWxUserSerialNo"))
                    .setOwnerRobotType(RobotType.valueOf(data.getInteger("ChatAdminType")))
                    .setType(data.getBooleanValue("IsEnterpriseChatroom") ? RoomType.WECOM : RoomType.WECHAT)
                    .setMemberCount(data.getInteger("nUserCount"));
            roomMapper.insert(room);
        }

        boolean robotRoomExists = isExists(robotId, roomId);
        if (robotRoomExists) {
            log.info("机器人-群关系已存在[robotId:{}, roomId:{}]", robotId, roomId);
        } else {
            RobotRoom robotRoom = new RobotRoom()
                    .setId(idGenerator.next())
                    .setRobotId(robotId)
                    .setRobotSerialNo(robotSerialNo)
                    .setRoomId(roomId)
                    .setRoomSerialNo(roomSerialNo)
                    .setRoomName(roomName)
                    .setInviterId(data.getString("vcFriendWxId"))
                    .setInviterSerialNo(data.getString("vcFriendSerialNo"))
                    .setInviterName(data.getString("vcNickName"))
                    .setInviterAvatar(data.getString("vcHeadImgUrl"))
                    .setCreatedTime(LocalDateTime.now());
            robotRoomMapper.insert(robotRoom);
        }
    }

    private boolean isExists(String roomId) {
        LambdaQueryWrapper<Room> wrapper = new LambdaQueryWrapper<Room>()
                .eq(Room::getId, roomId);
        return roomMapper.exists(wrapper);
    }

    private boolean isExists(String robotId, String roomId) {
        LambdaQueryWrapper<RobotRoom> wrapper = new LambdaQueryWrapper<RobotRoom>()
                .eq(RobotRoom::getRobotId, robotId)
                .eq(RobotRoom::getRoomId, roomId);
        return robotRoomMapper.exists(wrapper);
    }
}
